package com.zwz.crawler.basic;

import com.zwz.constant.Constant;
import com.zwz.entity.InformationChange;
import com.zwz.parse.JsonParserUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;



@Slf4j
public class TungeeAlterationQuery {
    public static  List<InformationChange> startTungeeAlterationQuery( String ENTERPRISE_ID) {
        // 请求参数配置
//        final String enterpriseId = "577de19eadf21dc4";
        final int start = 0;
        final int end = 10;

        InformationChange res=null;
        List<InformationChange> ret=null;
        // 参数验证
        validateParameters(start, end);

        try {
            // 构建URL（严格URL编码）
            String encodedId = URLEncoder.encode(ENTERPRISE_ID, String.valueOf(StandardCharsets.UTF_8));
            String url = String.format(
                    "https://sales.tungee.com/api/enterprise/detail/alteration-page?enterprise_id=%s&start=%d&end=%d",
                    encodedId, start, end
            );

            // 发送请求
            Connection.Response response = Jsoup.connect(url)
                    .method(Connection.Method.GET)
                    // 请求头配置（与浏览器完全一致）
                    .header("authority", "sales.tungee.com")
                    .header("accept", "*/*")
                    .header("accept-encoding", "gzip, deflate, br, zstd")
                    .header("accept-language", "zh-CN,zh;q=0.9")
                    .header("cache-control", "no-cache")
//                    .header("cookie", "_tx_pid=67864ea75f69e05d3b544ca7; __wpkreporterwid_=cc4a07fc-7bb9-40a4-96bc-2cbac34b658f; __last_enter_version=sales; _co_i=6805a5576eceb9637696f09d; _tx_uid=680701dddca941522b77e864; _tx_cid=6805a5576eceb9637696f09d; DISTINCT_ID=b84fe276-099f-4932-92b3-d54b92ae384b; _tx_sid=MTc0NTMwMTE0MzYyMjo4MmQ2OTQ5MTY0NjU2ODNmYjQ5MjlmMjc3NDg5ZDFlZg==; Hm_lvt_f2ee75449fc055cc4dbceb4fe403bea3=1745301094,1745302709; HMACCOUNT=B4E402DF057C895E; SecurityCenterDuId=ImFBSG15RzdPdVdPdCtsWnNGMFVuSXhVPSI.GujnjA.YBo4Zvc8vs4jgEmtioacknOQ9pE; tg_referrer_source=https%3A%2F%2Fcrm.tungee.com%2F; acw_tc=0a47308517453903928703142e006e6527c8b0eb5639732bfa5bd10fc7116d; Hm_lpvt_f2ee75449fc055cc4dbceb4fe403bea3=1745391920; accountCenterSessionId=.eJwlzsFKxDAQgOF3yXkPM5lpkt2b2sWL215WhF7KJJlQS6nQdlUU392i95-P_9v0ZdF1MKdtuenBrK_ZnExbD0PzlbCrn7e27obuAaC9NuPTy_mzebxszXhXXa7d1NRn6sb7wRzMrJr7Vd613976HM2pyLTuYP8HklAoATGCUnaUC5bgUDFr1Fg8eiUJycYMLKzMKSXvhQAsSIIjAPgSKIfAIozkI0mRKnm2qQKSmLmCjNEBB7COMbNasEVpl7Mn3Qdvqy7_My6Arxwkp0nj0VFURrTW7lEaZJ512qMPjebnFzoQVH8.Guoisg.RzmOB8rwO6PiO4JCVkLg_Tn8xTg; doncusSessionId=eyJfZnJlc2giOmZhbHNlLCJ1c2VyX2lkIjoiNjgwNzAxZGRkY2E5NDE1MjJiNzdlODY0In0.Guoi5Q.AOFywnwglpi_2Q4U1QtG1R3vIfE")
                    .header("cookie", Constant.cookies)
                    .header("pragma", "no-cache")
                    .header("priority", "u=1, i")
                    .header("referer", "https://sales.tungee.com/enterprise-details/577de19eadf21dc4/enterprise-information/basic-information")
                    .header("sec-ch-ua", "\"Not;A=Brand\";v=\"24\", \"Chromium\";v=\"128\"")
                    .header("sec-ch-ua-mobile", "?0")
                    .header("sec-ch-ua-platform", "\"Windows\"")
                    .header("sec-fetch-dest", "empty")
                    .header("sec-fetch-mode", "cors")
                    .header("sec-fetch-site", "same-origin")
                    .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36")
                    .header("x-tonxis-pid", "67864ea75f69e05d3b544ca7")
                    // 连接配置
                    .ignoreContentType(true)    // 允许非HTML响应
                    .ignoreHttpErrors(true)    // 不抛出HTTP错误
                    .maxBodySize(0)            // 禁用响应大小限制
                    .timeout(30_000)           // 30秒超时
                    .execute();

            // 响应处理
            processResponse(response, ENTERPRISE_ID);

            //解析parse
            ret = JsonParserUtil.parseChange(response.body());


        } catch (IOException e) {
            handleNetworkError(e);
        }
        return ret;


    }

    // 参数有效性校验
    private static void validateParameters(int start, int end) {
        if (start < 0 || end <= start || (end - start) > 100) {
            throw new IllegalArgumentException("分页参数不合法，要求：start >= 0 且 end > start 且 (end - start) <= 100");
        }
    }

    // 响应处理逻辑
    private static void processResponse(Connection.Response response, String enterpriseId) {
       log.info("HTTP状态码: " + response.statusCode());
//       //log.info("响应内容:\n" + response.body());
        switch (response.statusCode()) {
            case 200:
               log.info("请求成功，数据长度: " + response.body().length());
                break;
            case 401:
                System.err.println("[认证失败] 需要：");
                System.err.println("1. 检查Cookie中的accountCenterSessionId和doncusSessionId");
                System.err.println("2. 通过浏览器登录更新Cookie");
                break;
            case 403:
                System.err.println("[权限不足] 可能原因：");
                System.err.println("1. 企业ID " + enterpriseId + " 不属于当前账户");
                System.err.println("2. 当前套餐不支持变更记录查询");
                break;
            case 429:
                System.err.println("[请求频繁] 建议：");
                System.err.println("1. 添加随机延迟（推荐3-8秒）");
                System.err.println("2. 使用代理IP池轮换");
                break;
            default:
                System.err.println("异常响应: " + response.statusCode());
        }
    }

    // 网络异常处理
    private static void handleNetworkError(IOException e) {
        System.err.println("网络请求失败，原因：");
        if (e.getMessage().contains("timed out")) {
            System.err.println("1. 连接超时，请检查网络或增加超时时间");
        } else if (e.getMessage().contains("Unable to tunnel")) {
            System.err.println("2. 代理服务器配置错误");
        } else {
            e.printStackTrace();
        }
    }

    // 动态签名生成示例（如需）
    private static String generateSignature(String params) {
        // 示例伪代码（需根据实际加密规则实现）
        // String timestamp = String.valueOf(System.currentTimeMillis());
        // String raw = params + "|" + timestamp;
        // return HmacUtils.hmacSha256Hex("secret_key", raw);
        return "需根据实际加密规则生成";
    }
}